package com.crossriver.crgis.portlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.crossriver.crgis.database.model.Application_C_of_O;
import com.crossriver.crgis.database.model.Documents;
import com.crossriver.crgis.database.model.Supporting_Document;
import com.crossriver.crgis.database.service.Application_C_of_OLocalServiceUtil;
import com.crossriver.crgis.database.service.DocumentsLocalServiceUtil;
import com.crossriver.crgis.database.service.Supporting_DocumentLocalServiceUtil;
import com.crossriver.crgis.portlet.util.DownloadUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.Base64;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class Download
 */
public class Download extends MVCPortlet {
	
	private static Log log = LogFactory.getLog(Download.class);
 
	public void displaySupportingDocuments (ActionRequest actionRequest, 
			ActionResponse actionResponse) {
		
		//get the application ID
		
		
		String applicationId = ParamUtil.getString(actionRequest, "applicationId");
		//Supporting_DocumentLocalServiceUtil.getSupporting_DocumentByUserId(userId)
		
		ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest
		.getAttribute(WebKeys.THEME_DISPLAY);
		
		
		
		List<Supporting_Document> suppDocs = null;;
		try {
			
			
			List<Application_C_of_O> applications = Application_C_of_OLocalServiceUtil.
						getApplication_C_of_OByUserId(new Long(themeDisplay.getUserId()).toString());
			
			for (Iterator iterator = applications.iterator(); iterator.hasNext();) {
				Application_C_of_O application_C_of_O = (Application_C_of_O) iterator.next();
				
				suppDocs = Supporting_DocumentLocalServiceUtil.getSupporting_DocumentByApplId(application_C_of_O.getApplicationId());
			}
			
		} catch (SystemException e) {
			if (log.isDebugEnabled()){
			log.debug("Retrieving Application information failed >>" + e.getMessage() );
			}
			//do a page for application error.
			actionRequest.setAttribute("jspPage", "/html/application_cofo/ApplicationError.jsp");
	        actionResponse.setRenderParameter("jspPage", "/html/application_cofo/ApplicationError.jsp");
			
			SessionErrors.add(actionRequest, "application-error");
			
			e.printStackTrace();
			
			return;
		}

        return;
	}

	
	
   public void serveResource (
    		ResourceRequest resReq, ResourceResponse resRes)
    throws IOException, PortletException
    {
    	
    	HttpServletRequest convertReq = PortalUtil.getHttpServletRequest(resReq);
    	HttpServletRequest originalReq = PortalUtil.getOriginalServletRequest(convertReq);
    	      
     	//get the download type
    	String downloadType = resReq.getParameter("downloadType");
    	if("static".equalsIgnoreCase(downloadType)){
    		String staticFileLoc = this.getInitParameter("static-file-location");
        	
        	String fileNameToDownload = resReq.getParameter("fileName"); //originalReq.getParameter("_Download_fileName");
        	
        	System.out.println("fileNameToDownload new --->>>" + resReq.getParameter("fileName"));
        	
        	File newFile = new File( staticFileLoc + "//" + fileNameToDownload + ".pdf");
        	 
        	resRes.setContentType("application/pdf");
        	resRes.setContentLength((int) newFile.length());
        	
        	String newReplaced = fileNameToDownload.replaceAll(" ", "");
        	
        	resRes.setProperty("Content-Disposition", "attachment; filename=" + newReplaced +".pdf");
        	
        	FileInputStream fis = new FileInputStream (newFile) ;
        	
        	byte[] readStream = new byte [(int) newFile.length()];
    		fis.read(readStream );
        	
        	resRes.getPortletOutputStream().write(readStream);
        	
        	fis.close();
    	}else{
    		String documentId = resReq.getParameter("documentId"); 
    		
    		Supporting_Document supportDoc = DownloadUtil.getSupportingDocument(documentId);
    		
    		Documents document = DownloadUtil.getDocument(documentId);
    		
    		byte[] readStream = Base64.decode(document.getDocumentUpload());
    		
    		resRes.setProperty("Content-Disposition", "attachment; filename=" + supportDoc.getFileName().replaceAll(" ", "_") );
        	
    		resRes.getPortletOutputStream().write(readStream);
    	}
    	
    }
}
